<template>
<div>
<!-- 导航  -->
  <van-nav-bar
  title="黑马头条-登录"
  />
<!-- 表单输入 -->
  <van-cell-group>
    <van-field
    label="手机号"
    required
    v-model.trim="userinfo.mobile"
    placeholder = '请输入手机号'
    :error-message= 'errmessage'
     />
    <van-field
    type="password"
    label="密码"
    required
    v-model.trim="userinfo.code"
    placeholder = '请输入密码'
    :error-message= 'errpassword'
   />
  </van-cell-group>
<!-- 按钮 -->
  <div class="btn-wrap">
  <van-button type="info" class="btn" @click="hLogin">登录</van-button>
  <van-button round type="info" class="btn" @click="hUser">获取个人信息</van-button>
    当前是否登陆？{{ $store.state.tokenInfo.token ? '已登录' : '未登录' }}
  </div>
</div>
</template>

<script>
// 导入axios
import { login, getUsername } from '@/api/user.js'
export default {
  name: 'login',
  data () {
    return {
      userinfo: {
        mobile: '13911111111',
        code: '246810'
      },
      errmessage: '',
      errpassword: ''
    }
  },
  methods: {
    validtor () {
      this.errmessage = /\d{11}/.test(this.userinfo.mobile) ? '' : '手机号错误'
      this.errpassword = /\d{6}/.test(this.userinfo.mobile) ? '' : '密码错误'
      return (this.errmessage === '' && this.errpassword === '')
    },
    // 登录按钮
    async hLogin () {
      // TODO 表单验证
      if (!this.validtor) {
        return
      }
      // 发请求
      // (1)引入接口 (2)传参
      // 在点击后进行loading提示
      this.$toast.loading({
        duration: 0, // 持续展示taast 永不关闭
        overlay: true, // 整体添加一个遮罩
        message: '加载中...'
      })
      const { mobile, code } = this.userinfo
      try {
        const result = await login(mobile, code)
        console.log(result)
        // 获取个人资料
        // const userresult = await getUsername()
        // console.log(userresult)
        // 将获取到的token对象存入vuex容器中
        this.$store.commit('mSetToken', result.data.data)
        // 用户个人信息
        const res = await getUsername()
        // console.log('用户信息', res).
        this.$store.commit('mSetUserInfo', res.data.data)
        this.$toast.success('登录成功')
        // 根据 用户需要跳转 路由参数跳转
        const backto = this.$route.query.jumpto || '/'
        this.$router.push(backto)
      } catch (err) {
        console.log(err)
        alert('登陆失败')
        this.$toast.fail('登录失败')
      }
    },
    // 获取用户信息
    async hUser () {
      const result = await getUsername()
      console.log('用户信息', result)
    }
  }
}
</script>

<style lang = "less" scoped>
.btn-wrap {
    padding: 20px;
    .btn{
        width: 100%;
        background-color: #6db4fd;
        color: #fff;
    }
}
</style>
